var express = require('express');
var router = express.Router();

// 导入shortid
const shortid = require('shortid');

// 导入moment
const moment = require('moment');
const jwt = require('jsonwebtoken');
const AccountModel = require('../../module/accountModule');
// 校验 token 中间件
const checkJWTMiddleware = require('../../middlewares/checkJWTMiddleware');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

// 获取账单列表
router.get('/account', checkJWTMiddleware, function(req, res, next) {
  AccountModel.find().sort({ time: -1 }).exec()
  .then((data) => {
    res.json({
      code: "0000",
      msg: "获取账单成功",
      data: data,
    })
  }, (err) => {
    res.json({
      code: "1001",
      msg: "获取账单失败",
      data: null,
    })
    return;
  })
});

// 获取单个账单
router.get('/account/:id', checkJWTMiddleware, function(req, res, next) {
  let id = req.params.id;
  AccountModel.findById(id).then((data) => {
    res.json({
      code: "0000",
      msg: "获取账单成功",
      data: data,
    })
  }, (err) => {
    res.json({
      code: "1004",
      msg: "获取账单失败",
      data: err,
    })
    return;
  })
});

// 添加账单
router.post('/account', checkJWTMiddleware, function(req, res, next) {
  // 生成id
  // let id = shortid.generate();
  // 保存数据
  // db.get('accounts').unshift({id, ...req.body}).write();
  AccountModel.create({
    ...req.body,
    time: moment(req.body.time).toDate()
  }).then((data) => {
    // 成功的提示
    res.json({
      code: "0000",
      msg: "添加账单成功",
      data: data,
    });
  }, (err) => {
    res.json({
      code: "1002",
      msg: "添加账单失败",
      data: null,
    });
    return;
  })
});

// 创建账单页面
router.get('/account/create', checkJWTMiddleware, function(req, res, next) {
  res.render('create');
  // res.send('创建账单');
});

// 删除账单
router.delete('/account/:id', checkJWTMiddleware, function(req, res, next) {
  // 获取 params.id 参数
  let id = req.params.id;
  // 根据 id 删除数据
  // db.get('accounts').remove({id}).write();
  AccountModel.deleteOne({ _id: id }).then((data) => {
    // 响应成功的提示
    res.json({
      code: "0000",
      msg: "删除账单成功",
      data: data,
    });
  }, (err) => {
    res.json({
      code: "1003",
      msg: "删除账单失败",
      data: err.message,
    });
    return;
  })
});

// 更新单个账单
router.patch('/account/:id', checkJWTMiddleware, function(req, res, next) {
  let id = req.params.id;
  if (req.body.time) {
    // 将时间转换为日期格式
    req.body.time = moment(req.body.time).toDate();
  }
  AccountModel.updateOne({_id: id}, req.body).then((data) => {
    return data;
  }).then((data) => {
    AccountModel.findById(id).then((data) => {
      res.json({
        code: "0000",
        msg: "更新账单成功",
        data: data,
      })
    })
  }).catch((err) => {
    res.json({
      code: "1005",
      msg: "更新账单失败",
      data: err,
    })
    return;
  })
})

module.exports = router;
